package desktop.agent;
import javafx.stage.*;
import javafx.scene.image.*;
import javafx.scene.effect.*;
import javafx.scene.*;
import javafx.scene.paint.*;
import javafx.scene.text.*;
import javafx.animation.*;
import javafx.scene.input.*;
import javafx.scene.input.KeyEvent;
import javax.swing.JOptionPane;
import tweet.response.*;
import desktop.agent.*;


var cctServer = "{FX.getArgument('cctServer')}";
var agentName= "{FX.getArgument('agentName')}";
var agentPassword= "{FX.getArgument('agentPassword')}";
var agentDomain= "{FX.getArgument('agentDomain')}";
var phonesetLoginId= "{FX.getArgument('phonesetLoginId')}";


println("FX INPUT - CCT Server : {cctServer}");
println("FX INPUT - Agent Name : {agentName}");
println("FX INPUT - Agent Domain : {agentDomain}");
println("FX INPUT - Phoneset Login Id : {phonesetLoginId}");

var sessionService = new ServiceUtil(cctServer, agentName, agentPassword, agentDomain );
 
def logoutAgent = Image { url: "{__DIR__}images/AgentLogout.png"}; 
def playNormal = Image { url: "{__DIR__}images/AgentReady.png"};
def stopNormal = Image { url: "{__DIR__}images/AgentNotReady.png"};
 
var image = logoutAgent;
var ready = false;
var ringing = false;
var answered = false;
var loggedIn = false;
var inBrowser = true;
 

var myHeight = 140;
var myWidth = 120;

var glowLevel = 0.0;
var glow = Glow {
    level: bind glowLevel
}

var readyImage = stopNormal;
var notReadyImage = playNormal;
var logoutAgentImage = logoutAgent;
 


static var notifyListener:OICCADNotificationListener = OICCADNotificationListener {
      override public function actionPerformed(str:String): Void {
           	println("notification listener ACTION PERFORMED: {str}");
           	FX.deferAction(function() {
           	    
           	
           	if(str.equals("ACTIVE")){
           	    println("FX ACTIVE");
           		glowLevel = 0.0;
           		timeline.stop();
            	
          	    ringing = false;
          	    answered = true;
          	    
          	} else if(str.equals("RINGING")){
          	    println("FX RINGING");
           		timeline.play();
           	    ringing = true;
                answered = false;
                
           }  else if(str.equals("DROPPED")){
                println("FX DROPPED");
                glowLevel = 0.0;
                timeline.stop();
                ringing = false;
                answered = false;
                           
           } else if(str.equals("AGENT_READY")){
              
              println("FX AGENT_READY");
              ready = true;
              image = playNormal;
              println("FX AGENT_READY END");
              
          } else if(str.equals("AGENT_NOT_READY")){
            
               println("FX AGENT_NOT_READY");
               ready = false;
               glowLevel = 0.0;
               timeline.stop();
               if (loggedIn) {
               		image = stopNormal;
               }
               println("FX AGENT_NOT_READY END");
               
		  } else if(str.equals("LOGGED_IN")){
		    
		    println("FX AGENT LOGGED_IN");
		    loggedIn = true;
            println("FX AGENT LOGGED_IN END");
            
		 } else if(str.equals("LOGGED_OUT")){
		     
		     println("FX AGENT LOGGED_OUT");
		     loggedIn = false;
		     image = logoutAgent;
		     println("FX AGENT LOGGED_OUT END");
		}
	
       }); //end of defer function
           	
   }
}


function popWindow(myUser:String, message:String, sessionService:ServiceUtil, x:Long, y:Long){
    var mymessage : String;
    
    if (message == null) {
    	mymessage = sessionService.getIntrinsicsMessage();
    } else if (message.contains("twitter")) {
    	var tweetResponse : TweetResponse;
    	mymessage = sessionService.getIntrinsic("title");
    } else {
        mymessage = sessionService.getIntrinsicsMessage();
    }
    
    tweet.response.Main.popWindow(myUser,mymessage, sessionService, x, y, null);
    
}
 
  
 
var button = ImageView {image: bind image, 
                        effect: bind glow,
                         
			onMouseWheelMoved: function( event ) {
			    
			    if (loggedIn) {
			        if (ready) {
			         	if (ringing) {
			            	println("FX onMouseWheelMoved: -  ringing, about to go not ready");
			            	FX.deferAction(function() {sessionService.setReadyStatus(false);   });

			         	} else if (answered) {
			            
			            	println("FX onMouseWheelMoved: -  on call, about to go not ready");
			            	FX.deferAction(function() {sessionService.setReadyStatus(false); });
			         	}
				    } else {
					         println("FX onMouseWheelMoved - about to logout Agent");
							 FX.deferAction(function() { sessionService.logoutAgent(); });
				    }
			        
			    } else { //Not logged in so will login agent
			        println("FX onMouseWheelMoved - about to login Agent");
			         FX.deferAction(function() {sessionService.loginAgent(phonesetLoginId, "") });
			    }
			}//end of onMouseWheelMoved
               
                 
           
            onMouseClicked: function(event) {
                   // popWindow("test", "link", sessionService);
                  
                   
            	if (loggedIn){
                	if (ready) {
                    	
                    	if (ringing) {
                           	println("FX onMouseClicked: - loggedIn - ringing, about to accept");
                            //WANT TO ANSWER CALL HERE
                    		FX.deferAction(function() {
                    			sessionService.accept();
                    			popWindow(sessionService.getIntrinsic("title"), sessionService.getIntrinsic("link"), sessionService, event.screenX, event.screenY);
                    		});
                    			
                        } else if (answered) {
                            println("FX onMouseClicked: - loggedIn - on call, about to drop");
                            //DROP CALL
                            FX.deferAction(function() {sessionService.drop(); });
                        } else {
                        	println("FX onMouseClicked: - loggedIn - ready, about to set to NOT READY");
                       		FX.deferAction(function() { sessionService.setReadyStatus(false); });
                        }
                       		    	    
               		 } else { //LOGGED IN BUT NOT READY
           	         	println("FX onMouseClicked: - not ready, about to set READY");
                   		FX.deferAction(function() { sessionService.setReadyStatus(true); });
               		 }
               	} else { //Not LOGGED IN
               		println("FX onMouseClicked: - not logged in, about to login agent");
                    FX.deferAction(function() { sessionService.loginAgent(phonesetLoginId, ""); });
               	}
               	 
          } //end of onMouseClicked   
	         
	                      
	                      
		onMousePressed: function(event) {
   			X = event.sceneX - event.node.translateX;
   			Y = event.sceneY - event.node.translateY;
		}//end of onMousePressed 
   						     			
       	onMouseDragged: function(event) {
        	if (event.sceneX - X <0) {
            	event.node.translateX = 0;
            } else { 
             	if (event.sceneX - X > myWidth - image.width){
                	 event.node.translateX = myWidth - image.width;
             	} else {
                	 event.node.translateX = event.sceneX - X;
             	}
            }
             
            if (event.sceneY - Y <0) {
                 event.node.translateY = 0;
            } else {if (event.sceneY - Y > myHeight - image.height){
                 event.node.translateY = myHeight - image.height;
            } else{
                 event.node.translateY = event.sceneY - Y;
            }
        }
     }
                        
}			
 
var X: Number;
var Y: Number;

var tooltip = Text {
   content: bind if (ready) "Ready" else "Not Ready"
   translateX: bind button.translateX + 20
   translateY: bind button.translateY + 115
   opacity: 0.0
   font: Font {
       size: 12
       name: "Tahoma"
   }
   fill: Color.BLACK
 };
 
 
  
 var timeline = Timeline {
     repeatCount: 60
     autoReverse: true
     keyFrames: [
         KeyFrame {
             time: 0s
             values: [ glowLevel => 0.0 ]
         },
         KeyFrame {
             time: 1s
             values: [ glowLevel => 0.55 ]
         }
     ]
 }
 
 
 def appear = Timeline {
    keyFrames: [
    at(0s) {tooltip.opacity => 0.0},
    at(0.5s) {tooltip.opacity => 1.0}
    ]
 }
 


//ADD LISTENER 
sessionService.addListener(notifyListener);

//LOGIN THE AGENT
var aLong:Long;
 
//if(sessionService.loginAgentResult(phonesetLoginId, "")){
if(sessionService.loginAgentAS(phonesetLoginId, "")){
    loggedIn = true;
    ready = sessionService.getReadyStatus();
    if (ready) {
    	image = playNormal;
    	ready = true;
    } else {
        image = stopNormal;
        ready = false;
    }
    aLong = 0;
    //Should check if active on a call
    //tweet.response.Main.popWindow("", "", sessionService, aLong, aLong, "initialise");
}


var exitCalled: Boolean = false;

//The shutdown function gets called when browser & application are shut.
FX.addShutdownAction(function():Void {
	    println("FX shutdown action");
	    //Unsubscribe
	    sessionService.unsubscribe();
	    //Stop Notification Consumer ?
	    // Stop any Timelines if they have been created and started
	exitCalled = true;
});

//public function close() : Void {
    //sessionService.unsubscribe();
//} 

var scene: Scene = Scene {
    width: myWidth
    height: myHeight
    fill: Color.TRANSPARENT

      
        
    content: [
        Group { content:[ button, tooltip ] },
    ]  //end of content
    
};

Stage {
    title: "CC Agent"
    style: StageStyle.TRANSPARENT
    scene: scene
    
    onClose: function() {
        println("Unsubscribing from onClose...");
        sessionService.unsubscribe();   
        java.lang.Thread.currentThread().sleep(1000);
        println("Unsubscribed from onClose...");   
                    
    }
     extensions: [
                AppletStageExtension {
    
                shouldDragStart: function(e): Boolean {
                    return e.primaryButtonDown;
                }
                onDragStarted: function() {
                    inBrowser = false;
                }
                onAppletRestored: function() {
                    inBrowser = true;
                }
                useDefaultClose: false;
                
            }
        ] //end of extensions
    
    	
};




